<?php

class AdminCollege_Controller extends Admin_Controller {
    public function index(Request $request, Response $response) {
        $size = intval($request->size) ?: 30;
        $p = intval($request->p ?: 1);
        $from = ($p - 1) * $size;
        $q = new TrueQuery();
        if ($request->search) $q = new SearchQuery('name', $request->search);
        $colleges = College::find($q, ['from' => $from, 'size' => $size, 'sort' => ['created' => 'ASC']]);
        $page_nav['count'] = College::totalCount($q);
        $nav = new SubPages($size, $page_nav['count'], $p, 10, "/admin/College/?p=", 2);
        $page_nav['nav'] = $nav->subPageCss2();
        $response->append(new View('admin/college/list', compact('colleges', 'page_nav')));
    }

    public function delete(Request $request, Response $response) {
        if (!$request->path(3)) $response->alertErrorAndGoBack('请求无效！');
        /**
         * @var    College $college
         */
        if (!($college = College::load($request->path(3)))) $response->alertAndGoBack('该学院不存在！');
        $college->remove();
        $response->alertAndGoTo('删除成功！所有与该学院相关的记录都已删除!', '/admin/college/');
    }

    public function edit(Request $request, Response $response) {
        if (!$request->isPost()) {
            $id = $request->path(3);
            $data = College::load($id);
            if (!$id || !$data) $data = new College();
            $response->send(new View('admin/college/edit', compact('data')));
        }
        /**
         * @var    College $data
         */
        $data = College::createByRequest($request);
        $nullCheck = [
            'name' => '学院名称',
            'address' => '学院地址',
        ];
        foreach ($nullCheck as $item => $description) if (!$data->$item) $response->alertErrorAndGoBack("{$description}不能为空！");
        $data->save();
        $response->alertAndGoTo('操作成功!', '/admin/College/');
    }
}